import { defineStore } from 'pinia';
import { ref } from 'vue';
import axios from 'axios';

// 配置 axios 默认值
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;

export interface User {
  id: number;
  username: string;
  phone: string;
}

interface LoginData {
  username?: string;
  phone?: string;
  password: string;
}

interface RegisterData {
  username: string;
  password: string;
  phone: string;
}

export const useUserStore = defineStore('user', () => {
  const currentUser = ref<User | null>(null);
  const token = ref<string | null>(null);

  // 设置用户信息
  const setUser = (user: User | null) => {
    currentUser.value = user;
  };

  // 设置token
  const setToken = (newToken: string | null) => {
    console.log('设置token:', newToken);
    token.value = newToken;
    try {
      if (newToken) {
        // 直接使用localStorage API
        window.localStorage.setItem('token', newToken);
        // 立即验证是否保存成功
        const savedToken = window.localStorage.getItem('token');
        console.log('立即验证保存的token:', savedToken);
        if (savedToken !== newToken) {
          console.error('token保存验证失败: 保存的值与原始值不匹配');
          console.log('原始token:', newToken);
          console.log('保存的token:', savedToken);
        }
      } else {
        window.localStorage.removeItem('token');
        // 验证是否成功删除
        const checkToken = window.localStorage.getItem('token');
        if (checkToken !== null) {
          console.error('token删除验证失败: token仍然存在');
        }
      }
    } catch (error) {
      console.error('localStorage操作失败:', error);
    }
  };

  // 恢复用户状态
  const restoreUserState = async (userData: User) => {
    try {
      // 验证 token 是否有效
      const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/auth/verify`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (response.data.success) {
        setUser(userData);
        setToken(localStorage.getItem('token'));
        return true;
      } else {
        throw new Error('Token 无效');
      }
    } catch (error) {
      throw new Error('恢复用户状态失败');
    }
  };

  // 初始化：从localStorage加载token
  const init = () => {
    try {
      const savedToken = window.localStorage.getItem('token');
      console.log('初始化时读取的token:', savedToken);
      if (savedToken) {
        token.value = savedToken;
        // 验证token并获取用户信息
        restoreUserState(JSON.parse(window.localStorage.getItem('user') || '{}'));
      }
    } catch (error) {
      console.error('初始化失败:', error);
    }
  };

  const login = async (data: LoginData) => {
    try {
      const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/auth/login`, data);
      console.log('登录响应:', response.data);
      const { data: responseData } = response.data;
      console.log('responseData:', responseData);
      console.log('token:', responseData.token);
      
      // 确保token存在
      if (!responseData.token) {
        throw new Error('服务器未返回token');
      }
      
      // 先设置token
      setToken(responseData.token);
      // 再设置用户信息
      setUser(responseData.user);
      
      // 验证token是否成功保存
      const savedToken = localStorage.getItem('token');
      console.log('保存的token:', savedToken);
      
      return responseData.user;
    } catch (error: any) {
      console.error('登录错误:', error);
      throw new Error(error.response?.data?.message || '登录失败');
    }
  };

  const register = async (data: RegisterData) => {
    try {
      const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/auth/register`, data);
      return response.data;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '注册失败');
    }
  };

  // 登出
  const logout = () => {
    setUser(null);
    setToken(null);
  };

  return {
    currentUser,
    token,
    setUser,
    setToken,
    init,
    login,
    register,
    logout,
    restoreUserState
  };
}); 